package com.itee.street.excel;

import com.itee.core.util.StringCoder;
import com.itee.street.entity.Term;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

public class ImportXlsxData {

    public static List<Term> readExcel(File file,boolean reverse) throws Exception {
        FileInputStream input = new FileInputStream(file);
        XSSFWorkbook wb = new XSSFWorkbook(new BufferedInputStream(input));
        XSSFSheet sheet = wb.getSheetAt(0);
        XSSFRow row = sheet.getRow(0);
        //int colNum = row.getPhysicalNumberOfCells();
        int rowNum = sheet.getPhysicalNumberOfRows();
        List<Term> meters = new ArrayList<>();
        if (rowNum > 0) {
            for (int i = 0; i < rowNum; i++) {
                row = sheet.getRow(i);
                if (row == null) {
                    break;
                }
                Term term = new Term();
                XSSFCell cell= row.getCell(0);
                String termUid = getValue(cell);
                if (StringUtils.isNotBlank(termUid)) {
                    term.setTermUid(StringCoder.fillZeroLeft(termUid, 12));
                    if (reverse){
                        byte[] uidBcd = StringCoder.hexStringToByte(term.getTermUid());
                        ArrayUtils.reverse(uidBcd);
                        term.setTermUid(StringCoder.bytesToHexString(uidBcd));
                    }
                    //XSSFCell cell1= row.getCell(1);
                    //if (cell1 != null){
                    //    term.setPn(Integer.parseInt(getValue(cell1)));
                    //}
                    meters.add(term);
                }
            }
        }
        input.close();
//        wb.close();
        return meters;
    }

    private static String getValue(XSSFCell hssfCell){
        if(hssfCell.getCellType() == XSSFCell.CELL_TYPE_BOOLEAN){
            return String.valueOf(hssfCell.getBooleanCellValue());
        }else if(hssfCell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC){
            return String.valueOf((int) hssfCell.getNumericCellValue());
        }else if (hssfCell.getCellType() ==XSSFCell.CELL_TYPE_STRING){
            return String.valueOf(hssfCell.getStringCellValue());
        }else{
            return String.valueOf(hssfCell.getStringCellValue());
        }
    }

}
